import React, { Component } from 'react'

import { SearchBar, Toast } from 'antd-mobile'

import { getPostionCity } from '../../../utils/getCity'

import { getAreaHouseByName } from '../../../api/area'

import styles from './index.module.css'

export default class Search extends Component {
  // 当前城市id
  city = {}
  state = {
    // 搜索框的值
    searchTxt: '',
    tipsList: [],
  }
  componentDidMount() {
    this.loadGetCity()
  }

  async loadGetCity() {
    const res = await getPostionCity()
    this.city = res
  }

  // 渲染搜索结果列表
  renderTips = () => {
    const { tipsList } = this.state

    return tipsList.map((item) => (
      <li
        onClick={() => this.itemClick(item)}
        key={item.community}
        className={styles.tip}
      >
        {item.communityName}
      </li>
    ))
  }
  // 点击
  itemClick = (item) => {
    const { communityName, community } = item
    this.props.history.push({
      pathname: '/rent/add',
      state: {
        name: communityName,
        id: community,
      },
    })
  }

  // 输入框发生变化的回调
  onChange = (val) => {
    clearTimeout(this.setId)
    this.setState({
      searchTxt: val,
    })
    if (val.trim() === '')
      return this.setState({
        tipsList: [],
      })
    this.setId = setTimeout(() => {
      this.loadAreaList()
    }, 700)
  }

  // 获取搜索
  async loadAreaList() {
    const { data: res } = await getAreaHouseByName({
      name: this.state.searchTxt,
      id: this.city.value,
    })
    if (!res.body.length) return Toast.info('查无结果')
    this.setState({
      tipsList: res.body,
    })
  }

  render() {
    const { history } = this.props
    const { searchTxt } = this.state

    return (
      <div className={styles.root}>
        {/* 搜索框 */}
        <SearchBar
          placeholder="请输入小区或地址"
          value={searchTxt}
          showCancelButton={true}
          onCancel={() => history.replace('/rent/add')}
          onChange={this.onChange}
        />

        {/* 搜索提示列表 */}
        <ul className={styles.tips}>{this.renderTips()}</ul>
      </div>
    )
  }
}
